﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http.Extensions;

namespace FlowServe
{
    public class UniformResponseFilter:IAsyncResultFilter
    {
        private readonly ILogger<UniformResponseFilter> _logger;

        public UniformResponseFilter(ILogger<UniformResponseFilter> logger)
        {
            _logger = logger;
        }

        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // 如果已经是统一的响应格式，直接返回
            if (context.Result is ObjectResult objectResult && objectResult.Value is ResponseData)
            {
                await next();
                return;
            }

            // 如果是 ObjectResult 类型，包装为统一响应
            if (context.Result is ObjectResult result)
            {
                context.Result = new ObjectResult(new ResponseData
                {
                    StatusCode = 200, // 成功状态码
                    Error = "",
                    info= "Success",
                    Data = result.Value
                });
            }
            // 如果是 ContentResult 类型，处理为字符串返回
            else if (context.Result is ContentResult contentResult)
            {
                await next();
                return;
            }
            // 其他情况的处理，例如返回空内容
            else if (context.Result is EmptyResult)
            {
                context.Result = new ObjectResult(new ResponseData
                {
                    StatusCode = 200,
                    info = "",
                    Error = "No Content",
                    Data = null
                });
            }
            // 继续执行下一个中间件或过滤器
            await next();
        }
    }
}
